package com.backend.system.common;

import cn.dev33.satoken.stp.StpInterface;
import com.backend.system.dao.entity.Permission;
import com.backend.system.dao.entity.Role;
import com.backend.system.service.IPermissionService;
import com.backend.system.service.IRoleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类<br>
 * 参考：<a href="https://sa-token.cc/doc.html#/use/jur-auth">https://sa-token.cc/doc.html#/use/jur-auth</a>
 *
 * @author backend-manage
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private IRoleService roleService;

    @Resource
    private IPermissionService permissionService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        RequestHeaderUserInfo userInfo = RequestHolder.getUserInfo();
        Long roleId = userInfo.getRoleId();
        List<Permission> permissions = permissionService.getPermissionsByRoleId(roleId);
        return permissions.stream().map(Permission::getCode).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<Role> roles = roleService.getRolesByUserId(Long.valueOf(loginId.toString()));
        return roles.stream().map(Role::getCode).collect(Collectors.toList());
    }
}
